
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include "Objects.h"
#include "ObjectUser.h"
#include "Global.h"
namespace RisingStar
{
	
	CObjects::CObjects(string in):mOut(in)
	{
		//解析json报文
		AnalysisReport();
		//形成对象列表
		//解析对象类型，根据对象类型，匹配响应的类
		//返回类值，拼凑返回结果

	}
	
	CObjects::~CObjects()
	{

	}
	const string& CObjects::Out()
	{
		return mOut;
	}
	CObject::ObjectPtr CObjects::ProcessObject(string ObjectType, TObjectProperty& objProperty)
	{

		CObject::ObjectPtr  pObj= sGlobal.GetObjectCopy(ObjectType);
		if(pObj.get() != NULL)
		{
			//先将属性压入其中
			pObj->AttachObjectProperty(objProperty);
			string databaseKey = pObj->Code("数据库关键字");//pObj->Code("ProvinceCode") +  pObj->Code("CountyCode");
			DatabasePtr pData;
			if(mDatabases.find(databaseKey) == mDatabases.end())
			{				
				
				if(!sGlobal.GetDatabasePtr(databaseKey,pData))
				{
					cout<<RSTR("错误:")"获取数据库:"<<databaseKey<<endl;
					boost::throw_exception(runtime_error("无法建立数据库连接"));
				}
				
				mDatabases[databaseKey] = pData;
				//创建一个连接
			}
			pObj->AttachDatabase(mDatabases[databaseKey]);
			
			
		
			pObj->Go();
			
		}
			//pObj = new CObjectUser(objProperty);
			//CObject* npObj =  pObj->Copy();

		
		return pObj;
	}
	bool CObjects::AnalysisReport()
	{
		bool ret = true;
		boost::property_tree::ptree outRoot;
		stringstream ss(mOut);
		string rst = "success";
		try 
		{
			boost::property_tree::ptree root;			

			boost::property_tree::ptree objects;
			boost::property_tree::read_json(ss,root);
			
			boost::property_tree::ptree::iterator rootlIter = root.begin();
			for(; rootlIter != root.end(); ++rootlIter)
			{
				CObject::ObjectPtr pObj;

				string objectID = rootlIter->second.get<string>("objectID");
				
				if(OBJECT_ID_LENGTH != objectID.length())
				{
					boost::throw_exception(runtime_error((boost::format("对象ID长度需要是%d位，传进来的对象ID:%d,不符合")%OBJECT_ID_LENGTH%objectID.length()).str()));
				}
				
				string objType = objectID.substr(0,OBJECT_CODE_LENGTH).c_str();
				TObjectProperty objProperty;
				string requestID =  rootlIter->second.get<string>("requestID");
				boost::property_tree::ptree semaphoreIDs =  rootlIter->second.get_child("semaphoreIDs");				
				boost::property_tree::ptree::iterator semlIter;
				objProperty.property["objectID"] = objectID;
				objProperty.property["requestID"] = requestID;
				//cout<<"发现requestID:"<<requestID<<endl;
				//cout<<"objectID:"<<objectID<<endl;
				//cout<<"requestID:"<<requestID<<endl;
				
				if(requestID == "")
				{
					//有理由怀疑是查询操作
					//查询参数每页条数(countPerPage)，当前页面(page)
					if(rootlIter->second.find("countPerPage") != rootlIter->second.not_found())
					{
						objProperty.property["countPerPage"] = rootlIter->second.get<string>("countPerPage");
					}
					if(rootlIter->second.find("page") != rootlIter->second.not_found())
					{
						objProperty.property["page"] = rootlIter->second.get<string>("page");
					}					
				}
				
				for(semlIter = semaphoreIDs.begin();semlIter != semaphoreIDs.end();++semlIter)
				{
					string ID =  semlIter->second.get<string>("ID");
					if(ID.length() != SEM_ID_LENGTH)
					{
						boost::throw_exception(runtime_error((boost::format("信号ID长度需要是%d位，传进来的对象ID%d，不符合")%OBJECT_ID_LENGTH%ID.length()).str()));
					}
					
					int sn = atoi(ID.substr(0,SEM_SN_LENGTH).c_str());
					int serial = atoi(ID.substr(SEM_SN_LENGTH,SEM_SERIAL_LENGTH).c_str());
					//cout<<"sn:"<<sn<<" serial:"<<serial<<endl;
					
					boost::property_tree::ptree::iterator semPropertlIter;
					for(semPropertlIter = semlIter->second.begin();semPropertlIter != semlIter->second.end();++semPropertlIter)
					{
						objProperty.spArr[sn][serial][semPropertlIter->first] = semlIter->second.get<string>(semPropertlIter->first);
						//cout<<"semPropertlIter->first:"<<semPropertlIter->first<<endl;
					}
				}
				
				pObj = ProcessObject(objType,objProperty);
				
				if(pObj.get() == NULL)
				{
					boost::throw_exception(runtime_error("上报的报文里面存在无法识别的对象ID"));
				}
				
				const list<TObjectProperty> l= pObj->Out();
				
				list<TObjectProperty>::const_iterator olIter;
				for(olIter = l.begin();olIter != l.end(); ++olIter)
				{
					boost::property_tree::ptree obj;
					boost::property_tree::ptree semaphoreIDs;
					map<string,string>::const_iterator optlIter;
					for(optlIter = (*olIter).property.begin();optlIter != (*olIter).property.end();optlIter++)
					{
						obj.put(optlIter->first,optlIter->second);
					}
					
					map<int, map<int,map<string,string> > >::const_iterator _1semlIter;
					for(_1semlIter = (*olIter).spArr.begin();_1semlIter != (*olIter).spArr.end();++_1semlIter)
					{
						 map<int,map<string,string> >::const_iterator _2semlIter;
						 for(_2semlIter = _1semlIter->second.begin();_2semlIter != _1semlIter->second.end();++_2semlIter)
						 {
							 map<string,string>::const_iterator _3semlIter;
							 boost::property_tree::ptree sem;
							 for(_3semlIter = _2semlIter->second.begin();_3semlIter != _2semlIter->second.end();++_3semlIter)
							 {							 
								 sem.put(_3semlIter->first,_3semlIter->second);
							 }
							 semaphoreIDs.push_back(make_pair("",sem));
						 }
					}
					obj.put_child("semaphoreIDs",semaphoreIDs);
					objects.push_back(make_pair("",obj));	
				}
				outRoot.put_child("objects",objects);	
				
				
				//重新打包生成反馈函数
				//读取obj的id
				//读取obj的requstID
				//读取semaphoreIDs下面的信号列表
		
		 
			}

		} 
		catch (boost::exception &e) 
		{ 

			TRACE(RSTR("boost错误:")"%s\n",boost::diagnostic_information(e).c_str());//boost::diagnostic_information 会提取所有信息
			rst = boost::diagnostic_information(e).c_str();
			ret = false;
		} 
		catch(std::exception& e){//catch的前后顺序定义会有区别抓取的

			TRACE(RSTR("系统错误:")"%s\n",e.what());	
			rst = e.what();
			ret = false;

		}
		outRoot.put("result",rst);
		stringstream dd;
		write_json(dd,outRoot);
		mOut = "";
		mOut=dd.str();
		
		return ret;
	}
};